﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Grids;
using VAdvantage.Classes;
using System.IO;
using System.Windows.Data;

namespace VAdvantage.Controls
{
    public class VBinary:CButton,IControl,IEditingControl
    {

        public event EventHandler VetoableChangeListener;


        bool isVisualEditor = false;

        #region "Declaration"
        /* context Menu Strip */
        /*private ContextMenu _popupMenu = new ContextMenu();
         */

        private SL4PopupMenu.PopupMenu _popupMenu = new SL4PopupMenu.PopupMenu();


        /*Menu Item */
        //private MenuItem _save = new MenuItem();
        private SL4PopupMenu.PopupMenuItem _save = new SL4PopupMenu.PopupMenuItem();

        /* Menu Item */
        //private MenuItem _open = new MenuItem();
        private SL4PopupMenu.PopupMenuItem _open = new SL4PopupMenu.PopupMenuItem();

        /** column Name             */
        private String _columnName;
        /** windowNo                */
        private int _windowNo;
        /** value 					*/
        private Object _data = null;
        /**	Logger			*/
        private static VLogger log = null;
        /** Grid Field				*/
        private GridField _field = null;
        /* displayType*/
        private int _displayType = DisplayType.Binary;
        /*mandatory */
        private bool _mandatory = false;
        /* readonly*/
        private bool _readOnly = false;

        Binding binding = null;

        #endregion


        public static readonly DependencyProperty ValueChangedProperty =
       DependencyProperty.Register("Value", typeof(Object), typeof(VAdvantage.Controls.VBinary), new PropertyMetadata((o, e) =>
       {
           ((VBinary)o).SetValue((Object)e.NewValue);

       }));


        public Object Value
        {
            get
            {
                return ((Object)GetValue(VBinary.ValueChangedProperty));
            }
            set
            {
                SetValue(VBinary.ValueChangedProperty, value);
            }
        }


        public  VBinary()
        {
           _save.Header= Utility.Msg.GetMsg("SaveTolocalFile");
           _open.Header = Utility.Msg.GetMsg("Open/LoadIntoDatabase");

           _save.Click += _save_Click;
           _open.Click += _open_Click;
        }

        /// <summary>
        ///constructor (called form VControlFactory)
        /// </summary>
        /// <param name="columnName">column name</param>
        /// <param name="WindowNo">windowNo</param>
        public VBinary(String columnName, int windowNo)
        {
            _columnName = columnName;
            log = VLogger.GetVLogger(typeof(VBinary).FullName);
            //this.Name = columnName;
            _windowNo = windowNo;
            //super.addActionListener(this);
            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                _save.Header = Utility.Msg.GetMsg("SaveTolocalFile");
                _open.Header = Utility.Msg.GetMsg("Open/LoadIntoDatabase");
                SetPopup();
                _save.Click += _save_Click;
                _open.Click += _open_Click;
            }
            else
            {
                isVisualEditor = true;
            }

            //this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;
            //this.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //this.Width = 300;
        }

       

        #region

        public int GetDisplayType()
        {
            return _displayType;
        }

        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            this.IsEnabled = !readOnly;
        }

        public Grids.GridField GetField()
        {
            return _field;
        }

        public void SetField(Grids.GridField mField)
        {
            if (mField != null)
                _windowNo = mField.GetWindowNo();
            _field = mField;
        }

        public string GetName()
        {
            return _columnName;
        }

        public void SetName(string name)
        {
            _columnName = name;
        }

        public string GetText()
        {
            return "";
        }

        public object GetValue()
        {
                return _data;
        }

        public void SetValue(object value)
        {
            if (DBNull.Value.Equals(value))
            {
                value = null;
            }
            _data = value;
            if (_data == null)
                this.Content = "-";
            else
            {
                String text = "?";
                if (_data is byte[])
                {
                    byte[] bb = (byte[])_data;
                    text = "#" + bb.Length;
                }
                else
                {
                    text = _data.GetType().FullName;
                    int index = text.LastIndexOf(".");
                    if (index != -1)
                        text = text.Substring(index + 1);
                }
                this.Content = text;
            }
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        public void SetBackGround(bool value)
        {
            //throw new NotImplementedException();
        }

        public string GetSelectedText()
        {
            return "";
        }

        public bool IsDisabled()
        {
            return this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return true; }
        }

        public string BindValue
        {
            set {

                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VBinary.ValueChangedProperty, binding);
            }
        }


        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }
#endregion


        /// <summary>
        /// Click Eventhandler Open Dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _open_Click(object sender, RoutedEventArgs e)
        {
            FileAction(false);
        }
        void _save_Click(object sender, RoutedEventArgs e)
        {
            FileAction(true);
        }
        


        /// <summary>
        ///File action
        /// </summary>
        /// <param name="save">true=save to file - false=load to db</param>
        private void FileAction(bool save)
        {

            bool isChanged = false;

            try
            {
                if (save && _data != null)
                {
                    SaveFileDialog sd = new SaveFileDialog();
                    sd.DefaultExt = ".txt";
                    sd.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*";
                    sd.FilterIndex = 2;  
                    log.Info(sd.SafeFileName);
                    if (sd.ShowDialog() == true)
                    {
                        Stream strm = sd.OpenFile();
                        Byte[] buffer = (Byte[])_data;
                        strm.Write(buffer, 0, buffer.Length);
                        strm.Flush();
                        strm.Close();
                        log.Config("Save to " + sd.SafeFileName + " #" + buffer.Length);
                    }

                }
                else
                {
                    OpenFileDialog od = new OpenFileDialog();
                    if (od.ShowDialog() == true)
                    {
                        FileInfo fInfo = od.File;

                        Stream strm = fInfo.OpenRead();

                        Byte[] buffer = new Byte[1024 * 8];   //  8kB

                        BinaryReader br = new BinaryReader(strm);
                        int length = int.MaxValue;
                        try
                        {
                            length = Convert.ToInt32(strm.Length);
                        }
                        catch
                        {
                        }

                        Byte[] data = br.ReadBytes(length);// strm.os.toByteArray();
                        if (data != null && !data.Equals(_data))
                        {
                            isChanged = true;
                        }
                        _data = data;

                        br.Close();
                        if (strm != null)
                        {
                            //strm.Flush();
                            strm.Close();
                        }
                        log.Config("Load from " + fInfo.FullName + " #" + data.Length);

                    }
                }
            }
            catch (Exception ex)
            {
                log.Log(Level.WARNING, "Save=" + save, ex);
            }

            try
            {
                if (isChanged)
                {
                    if (EditingControlDataGridView != null)
                    {
                        EditingControlDataGridView.RaiseCellValueChanged(this);
                        object newValue = GetValue();
                        _field.SetValue(newValue);
                        ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), newValue);
                    }
                    else
                    {
                        if (VetoableChangeListener != null)

                            VetoableChangeListener(this, EventArgs.Empty);
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// Set Attibute for gridview editing control
        /// </summary>
        /// <param name="field">field object</param>
        public void SetAttributes(GridField field)
        {
            _columnName = field.GetColumnName();
            if (log == null)
            {
                log = VLogger.GetVLogger(typeof(VBinary).FullName);
            }
            this.Name = _columnName;
            _readOnly = field.IsReadOnly();
            _mandatory = field.IsMandatory(false);
            SetPopup();
            SetField(field);
            //SetValue(EditingControlDataGridView.CurrentCell.Value);
        }

        /// <summary>
        /// Add menu item in popup
        /// </summary>
        private void SetPopup()
        {
            _popupMenu.Items.Clear();
            _popupMenu.Items.Add(_save);
            _popupMenu.Items.Add(_open);

            _popupMenu.AddTrigger(SL4PopupMenu.TriggerTypes.LeftClick, this);

            //ContextMenuService.SetContextMenu(this, _popupMenu);
        }



        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }
    }
}
